<?php

/**
 * 客户（方）订单
 *
 * @author cdlei
 */

require_once 'CommonController.php';

class Admin_OrderPartnerController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->_model = new Application_Model_OrderPartner();
        $this->view->title = "管理中心";
    }

    /**
     * 导入
     * 
     * @return void
     */
    public function importAction()
    {
        $products = array('yintai');
        $demoFiles = array('yintai'=>'/data/orderPartnerDemo/yintai.xls');
        $currentProductCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();

        if (!in_array($currentProductCode, $products)) {
            exit('该产品的导入功能没有开启。');
        }
        $this->view->demoUrl = $demoFiles[$currentProductCode];

        if ($this->_request->isPost()) {
            if (!is_uploaded_file($_FILES['uploadfile']['tmp_name'])) {
                echo $this->view->message('上传错误！') ;
                exit;
            }
            if ($_FILES["uploadfile"]["size"] > 10000000) { //1M
                echo $this->view->message('上传文件不能大于1MB！') ;
                exit;
            }

            $fileType = $this->_request->get('fileType');
            $ext = strtolower(substr($_FILES['uploadfile']['name'], strrpos($_FILES['uploadfile']['name'], '.') + 1));

            if ($currentProductCode == 'yintai') {
                if ($ext == 'xls' || $ext == 'xlsx') {
                    $configs = array(
                        'productCode' => $currentProductCode,
                        'osName' => '{2}',
                        'orderId' => '{5}',
                        'createTime' => '{4}',
                        'updateTime' => '{4}',
                        'addTime' => date("Y-m-d H:i:s"),
                        'amount' => '{6}',
                        'orderStatus' => '{7}',
                        'promotionId' => '{3}',
                        'sourceId' => '',
                        'sourceSubId' => '',
                        'userRegisterType' => '',
                    );
                    $file = $_FILES["uploadfile"]["tmp_name"];
                    $objPHPExcel = PHPExcel_IOFactory::load($file);
                    $objWorksheet = $objPHPExcel->getActiveSheet();
                    $highestRow = $objWorksheet->getHighestRow();

                    $rows = array();
                    $orderIds = array();
                    $minDate = NULL;
                    $maxDate = NULL;
                    for ($i = 1; $i <= $highestRow; $i++) {
                        $n = $i - 1;
                        $field = $configs;
                        foreach ($field as $key=>$value) {
                            preg_match_all("|^\{(\d+)\}$|", $value, $result);
                            if (isset($result[1][0])) {
                                $field[$key] = @trim($objWorksheet->getCellByColumnAndRow($result[1][0], $i)->getFormattedValue());
                            }
                        }
                        $field['createTime'] = date("Y-m-d H:i:s", strtotime($field['createTime']));
                        $field['updateTime'] = date("Y-m-d H:i:s", strtotime($field['updateTime']));
                        $field['osName'] = strtolower($field['osName']);
                        if (strtotime($field['createTime']) == 0) {
                            continue;
                        }
                        $orderIds[] = addslashes(strtolower($field['orderId']));
                        $rows[] = $field;
                    }

                    $existsOrderIds = array();
                    if (!empty($orderIds)) {
                        $existsRows = $this->_model->fetchAll("`productCode` = '{$currentProductCode}' AND `orderId` IN ('". implode("', '", $orderIds) ."')");
                        foreach($existsRows as $existsRow) {
                            $existsOrderIds[] = strtolower($existsRow['orderId']);
                        }
                    }

                    $msg = '';
                    $importRight = 0;
                    $importError = 0;

                    foreach($rows as $key=>$row) {
                        $i = $key + 1;
                        if ($row['orderId'] == '') {
                            $msg .= !empty($msg) ? '<br/>' : $msg;
                            $msg .= "第{$i}行导入失败，订单号为空。";
                            $importError++;
                            continue;
                        }
                        if (!is_numeric($row['amount'])) {
                            $msg .= !empty($msg) ? '<br/>' : $msg;
                            $msg .= "第{$i}行导入失败，金额填写错误。";
                            $importError++;
                            continue;
                        }
                        if (!in_array($row['orderId'], $existsOrderIds)) {
                            $this->_model->insert($row);
                            $msg .= !empty($msg) ? '<br/>' : $msg;
                            $msg .= "第{$i}行导入完成。";

                            //处理统计使用的时间
                            $minDate = $minDate === NULL ? $row['createTime'] : $minDate;
                            if (strtotime($row['createTime']) < strtotime($minDate)) {
                                $minDate = $row['createTime'];
                            }
                            $maxDate = $maxDate === NULL ? $row['createTime'] : $maxDate;
                            if (strtotime($row['createTime']) > strtotime($maxDate)) {
                                $maxDate = $row['createTime'];
                            }
                            $importRight++;
                        } else {
                            $msg .= !empty($msg) ? '<br/>' : $msg;
                            $msg .= "第{$i}行导入失败，订单“{$row['orderId']}”已经存在。"; 
                            $importError++;
                            continue;
                        }
                    }

                    if (!empty($minDate) && !empty($maxDate))  {
                        $this->_model->getAdapter()->getConnection()->query("CALL mob_day_partner_statistics_by_date('{$currentProductCode}', '{$minDate}', '{$maxDate}')");
                    }
                    echo "{$msg}<br><b>共处理" . ($importRight + $importError) . '条记录，' . "导人成功{$importRight}条，失败{$importError}条，<a href=\"". $this->view->projectUrl() ."\">返回</a></b>";
                    exit;
                } else {
                    echo $this->view->message('你只能上传文件格式“{$ext}”不被支持！') ;
                    exit;
                }
            }
            
        }
    }
}